<template>
    <el-row v-show="showLoginUI">
        <el-col :span="2">
            用户：
        </el-col>
        <el-col :span="5">
            <el-input v-model="username" placeholder="用户名" />
        </el-col>
        <el-col :span="3">
            <el-button @click="login">登录</el-button>
        </el-col>
    </el-row>

    <div v-show="showHallUI">
        <el-row>
            <el-col :span="5">
                <el-input v-model="roomName" placeholder="房间名称" />
            </el-col>
            <el-col :span="3">
                <el-button @click="createRoom">创建房间</el-button>
            </el-col>
        </el-row>
        <el-row>
            <el-col :span="5">
                <el-input v-model="roomId" placeholder="房间号" />
            </el-col>
            <el-col :span="3">
                <el-button @click="joinRoom">加入房间</el-button>
            </el-col>
        </el-row>
    </div>

    <div v-show="showGameRoomUI">
        <el-row>
            <el-col :span="3">
                <el-tag>{{ gameRoomId }}</el-tag>
            </el-col>
            <el-col :span="3">
                <el-tag class="ml-2" type="success">{{ gameRoomName }}</el-tag>
            </el-col>
            <el-col :span="5" v-show="isMaster === '1' && !isGameStart">
                <el-button  @click="startGame" type="primary">开始</el-button>
            </el-col>
            <el-col :span="8" v-show="speakPlayer !== ''">
                【{{ speakPlayer }}】【{{ speakNum }}个{{ speakDice }} {{ modeList[speakType].name }}】      下一位【{{ speakNext }}】
            </el-col>
            <el-col :span="8" v-show="speakPlayer === '' && speakNext !== ''">
                当前【{{ speakNext }}】
            </el-col>
            <el-col :span="5" v-show="isMeCheck && speakPlayer !== ''">
                <el-button @click="openTheDice" type="primary">开</el-button>
            </el-col>
        </el-row>
        <br/>

        <el-row>
            <el-col :span="12">
                <el-card class="box-card"  v-for="item in playerList">
                    <template #header>
                        <div class="card-header">
                            <span>{{ item.username }} <el-tag class="ml-2" type="success">{{ item.grade }}</el-tag></span>
                            <el-col :span="5" v-show="isMaster === '1' && !isGameStart && username !== item.username">
                                <el-button @click="kickAss(item.username)" type="primary">踢出</el-button>
                            </el-col>
                            <div v-show="isMeCheck && item.username === username">
                                <el-row justify="end" align="middle">
                                    <el-col :span="4">
                                        <el-select v-model="checkNum" class="m-1" placeholder="数量">
                                            <el-option v-for="item in 20" :key="item" :value="item" />
                                        </el-select>
                                    </el-col>
                                    <el-col :span="2" >
                                        <el-text >个</el-text>
                                    </el-col>
                                    <el-col :span="4">
                                        <el-select v-model="checkDice" class="m-2" placeholder="骰子">
                                            <el-option v-for="item in 6" :key="item" :value="item" />
                                        </el-select>
                                    </el-col>
                                    <el-col :span="4">
                                        <el-select v-model="diceType" class="m-2" placeholder="模式">
                                            <el-option v-for="item in modeList" :key="item" :label="item.name" :value="item.value" />
                                        </el-select>
                                    </el-col>
                                    <el-col :span="4">
                                        <el-button  @click="sendDiceCheck" type="primary">确认</el-button>
                                    </el-col>
                                </el-row>
                            </div>
                        </div>
                    </template>
                    <el-row v-show="initDice.has(item.username)">
                        <el-col :span="4" v-for="(it,index) in initDice.get(item.username)" >
                            <div v-if="showWinDice" :class="[ showWinDice && (it === speakDice || (diceType === 0 && it === '1')) ? 'showRedBorder' : 'showGrayBorder' ]" style="width: 50px;height: 50px; text-align: center;">
                                {{ it }}
                            </div>
                            <div v-if="!showWinDice" style="width: 50px;height: 50px;border: gray 1px solid; text-align: center">
                                {{ it }}
                            </div>
                            <span v-if="index === 5"> 豹子 </span>
                        </el-col>
                    </el-row>
                    <el-row v-show="!initDice.has(item.username)">
                        <el-col :span="4" v-for="o in 5" >
                            <div style="width: 50px;height: 50px;border: gray 1px solid; text-align: center">
                            </div>
                        </el-col>
                    </el-row>
                </el-card>
            </el-col>
            <el-col :span="12">
                <ul style="overflow: auto; height: 300px;border: gray 1px solid;">
                    <li v-for="i in msgList" >{{ i }}</li>
                </ul>
                <br>
                <ul style="overflow: auto; height: 300px;border: gray 1px solid; margin-bottom: 5px">
                    <li v-for="i in chatList" >{{ i.user }} : {{ i.msg }}</li>
                </ul>
                <el-input v-model="myMsg" @keyup.enter.native="sendMsg" :rows="2" type="textarea"  />
                <el-row justify="end" style="margin-top: 5px">
                    <el-col :span="4">
                        <el-button @click="clearChat">清屏</el-button>
                    </el-col>
                    <el-col :span="4">
                        <el-button @click="sendMsg">发送</el-button>
                    </el-col>

                </el-row>

            </el-col>
        </el-row>
    </div>


</template>

<script setup lang="ts">
import {reactive, ref, watch} from "vue";
import {webSocket} from "@/utils/websocket";
import {ElMessage} from "element-plus";

if (window.Notification) {
    // 浏览器通知--window.Notification
    if (Notification.permission == "granted") {
        console.log("允许通知")
    }else if( Notification.permission != "denied"){
        console.log("需要通知权限")
        Notification.requestPermission((permission)=> {});
    }
} else {
    console.error('浏览器不支持Notification');
}

const wx = reactive(new webSocket('ws://43.139.72.119:9529/game'))
// const wx = reactive(new webSocket('ws://192.168.7.41:9529/game'))
watch(() => wx.callData, (callData) => {
    if (callData == '') {
        return;
    }
    console.log("↓：" + callData);
    const array_msg = callData.split('|');
    wx.callData = "";
    if (array_msg[0] === "LOGIN_SUC") {
        username.value = array_msg[1];
        showLoginUI.value = false;
        showHallUI.value = true;
    }
    if (array_msg[0] === "ROOM_CREATE"){
        showHallUI.value = false;
        showGameRoomUI.value = true;
        handleRoomInfo(array_msg);
    }
    if (array_msg[0] === 'JOIN_ROOM'){
        handleJoinRoom(array_msg);
    }
    if (array_msg[0] === 'DICE_LIST'){
        handleDiceList(array_msg[1]);
    }
    if (array_msg[0] === 'GAME_START'){
        handleGameStart(array_msg[1]);
    }
    if (array_msg[0] === 'DICE_CALL'){
        handleDiceCall(array_msg[1])
    }
    if (array_msg[0] === 'GRADE_INFO'){
        handleGradeInfo(array_msg[1], array_msg[2])
    }
    if (array_msg[0] === 'SEND_MSG'){
        handleMsgInfo(array_msg[1], array_msg[2]);
    }
    if (array_msg[0] === 'KICK_ASS'){
        handleKickAss(array_msg[1]);
    }
    if (array_msg[0] === 'WHO_CALL'){
        handleWhoCall(array_msg[1])
    }
    if (array_msg[0] === 'error') {
        ElMessage.error(array_msg[1])
    }
});

// 登录页面逻辑
let showLoginUI = ref(true);
let username = ref("");
function login(){
    wx.connect("10001|" + username.value)
}

// 大厅页面逻辑
let showHallUI = ref(false)
let roomId = ref("")
let roomName = ref("")
let initNum = ref(0);
function createRoom(){
    wx.send("10002|" + roomName.value);
    initDice.value.set(username.value, ["0", "0", "0", "0", "0"])
}
function joinRoom(){
    wx.send("10003|" + roomId.value);
}

// 游戏房间逻辑
interface PlayerInfo{
    username: string
    grade: string
}
let showGameRoomUI = ref(false);
let gameRoomId = ref("");
let gameRoomName = ref("");
let playerList = ref<PlayerInfo[]>([]);
let isMaster = ref("0");
function handleRoomInfo(data: string[]){
    isMaster.value = data[3];
    let roomInfoArr = data[1].split("-");
    gameRoomId.value = roomInfoArr[0];
    gameRoomName.value = roomInfoArr[1];

    data[2].split("=").forEach((item, idx) => {
        let playerArr = item.split("-");
        playerList.value.push({
            username: playerArr[0],
            grade: "0"
        })
    })

    initNum.value = playerList.value.length;
}
function kickAss(username: string){
    wx.send("10007|" + username)
}
// 加入房间逻辑
function handleJoinRoom(data: string[]){
    playerList.value.push({
        username: data[1],
        grade: "0"
    })
    initNum.value = playerList.value.length;
}
function handleKickAss(playId: string){
    if (username.value == playId){
        playerList.value = [];
        msgList.value = [];
        chatList.value = [];
        showGameRoomUI.value = false;
        showHallUI.value = true;
    }else {
        playerList.value = playerList.value.filter(e => e.username != playId)
    }
}

// 开始游戏逻辑
let msgList = ref<string[]>([]);
let modeList = [
    {
        "name": "普通",
        "value": 0
    },
    {
        "name": "栽",
        "value": 1
    }
]
let isGameStart = ref(false);
let initDice = ref(new Map)
function startGame(){
    wx.send("10006|");
}
function handleDiceList(dice: string){
    showWinDice.value = false;
    initDice.value = new Map;
    isGameStart.value = true;
    initDice.value.set(username.value, dice.split("-"))
}

// 开始游戏并叫骰子
let isMeCheck = ref(false);
let checkNum = ref(0);
let minCheckNum = ref(0);
let checkDice = ref(1);
let diceType = ref(0)
function handleGameStart(initStr: string){
    isMeCheck.value = true;
    let initArr = initStr.split("-");
    checkNum.value = Number(initArr[0]);
    minCheckNum.value = Number(initArr[0]);
    checkDice.value = Number(initArr[1])
    diceType.value = Number(initArr[2])

    if( Notification.permission != "denied"){
        console.log("需要通知权限")
        Notification.requestPermission((permission)=> {});
    }
    let n = new Notification('多喝热水', {
        body: '到你了',
        icon: ''
    })
    setTimeout(() => {
        n.close();
    }, 3000)
}
function sendDiceCheck(){
    if (checkDice.value == 1){
        diceType.value = 1;
    }
    // if (checkNum.value < minCheckNum.value){
    //     ElMessage.error("当前最小应该叫：" + minCheckNum.value + "个");
    //     return;
    // }
    isMeCheck.value = false;
    wx.send("20001|" + diceType.value + "|" + checkNum.value + "|" + checkDice.value);
}
let speakPlayer = ref("");
let speakType = ref(0);
let speakNum = ref("")
let speakDice = ref("")
let speakNext = ref("")
function handleDiceCall(call: string){
    let callArr = call.split("-");
    speakPlayer.value = callArr[0];
    speakType.value = Number(callArr[1])
    speakNum.value = callArr[2];
    speakDice.value = callArr[3];
    speakNext.value = callArr[4];

    msgList.value.push("【" + speakPlayer.value + "】:" + speakNum.value + "个" + speakDice.value + "-" + modeList[speakType.value].name )
}
function openTheDice(){
    wx.send("20002|");
}
function handleWhoCall(playId: string){
    speakNext.value = playId;
}

// 结算逻辑
let showWinDice = ref(false);
function handleGradeInfo(grade: string, diceStr: string){
    showWinDice.value = true;
    diceStr.split("=").forEach(item => {
        let diceArr = item.split("-");
        let strList = [diceArr[1], diceArr[2], diceArr[3], diceArr[4], diceArr[5]];
        let newList = Array.from(new Set(strList))
        if (newList.length == 1){
            strList.push(strList[0]);
        }
        initDice.value.set(diceArr[0], strList);
    });

    let gradeArr = grade.split("-");
    diceType.value = Number(gradeArr[2]);
    playerList.value.forEach(info =>{
        if (info.username === gradeArr[0]){
            info.grade = gradeArr[1];
        }
    })


    msgList.value.push("玩家：【" + gradeArr[0] + "】失败")
    msgList.value.push("--------------------------------");

    isGameStart.value = false;
    isMeCheck.value = false;
    checkNum.value = 0;
    checkDice.value = 1;

    speakPlayer.value = "";
}

// UI 逻辑
let myMsg = ref("");
let chatList = ref<ChatMsgInfo[]>([]);
function clearChat(){
    msgList.value = [];
    chatList.value = [];
}
function sendMsg(){
    if (myMsg.value.includes("|")){
        ElMessage.error("不能发送特殊字符");
    }
    wx.send("30001|" + myMsg.value);
    myMsg.value = "";
}
interface ChatMsgInfo{
    user: string,
    msg: string
}
function handleMsgInfo(player: string, msg: string){
    chatList.value.push({
        user: player,
        msg: msg
    })
    let n = new Notification('多喝热水', {
        body: player + '：' + msg,
        icon: ''
    })
    setTimeout(() => {
        n.close();
    }, 1000)
}

</script>

<style scoped>
.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 5px;
}
.showRedBorder{
    border: red 1px solid;
    color: red;
}
.showGrayBorder{
    border: gray 1px solid;
    color: gray;
}

</style>